package net.oschina.allchat.message.processing.conversion;

import java.lang.annotation.Annotation;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ConversionFactory implements IConversionFactory {
	private Map<Class<?>, IConverterFactory<?>> converterFactories;
	
	public ConversionFactory() {
		this.converterFactories = new ConcurrentHashMap<Class<?>, IConverterFactory<?>>();
	}

	@Override
	public <T extends Annotation> void register(Class<T> type, IConverterFactory<T> converterFactory) {
		converterFactories.put(type, converterFactory);
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T extends Annotation> IConverterFactory<T> unregister(Class<T> type) {
		return (IConverterFactory<T>)converterFactories.remove(type);
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T extends Annotation> IConverter getConverter(T annotation) {
		IConverterFactory<T> factory = (IConverterFactory<T>)converterFactories.get(annotation.annotationType());
		if (factory == null)
			return null;
		
		return factory.create(annotation);
	}

}
